package com.hmall.search.listen;

import com.alibaba.fastjson.JSON;
import com.hmall.common.constant.MqConstant;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author Vsunks.v
 * @Date 2022/8/11 17:58
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description:
 */
@Component
public class ItemListen {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(MqConstant.ITEM_INSERT_QUEUE),
                    exchange = @Exchange(value = MqConstant.ITEM_EXCHANGE,type = ExchangeTypes.DIRECT),
                    key = MqConstant.ITEM_INSERT_KEY
            )
    })
    public void listenItemInsert(String itemStr) throws IOException {
        Item item = JSON.parseObject(itemStr, Item.class);
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest indexRequest = new IndexRequest(EsConstant.ITEM_INDEX);
        indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON )
        .id(itemDoc.getId().toString());
        client.index(indexRequest, RequestOptions.DEFAULT);
    }

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(MqConstant.ITEM_DELETE_QUEUE),
            exchange = @Exchange(value = MqConstant.ITEM_EXCHANGE,type = ExchangeTypes.DIRECT),
            key = MqConstant.ITEM_DELETE_KEY)
    })
    public void listenItemDelete(String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(EsConstant.ITEM_INDEX, id);
        client.delete(deleteRequest,RequestOptions.DEFAULT );
    }
}
